<template>
  <div class="site-tools">
    <float-button type="primary" @click="openSiteModal">
      <template #icon>
        <Icon icon="humbleicons:exchange-horizontal" />
      </template>
      <template #tooltip>
        <div>{{
          getCurrentSite?.name ? `当前：${getCurrentSite?.name}，点击可切换站点` : '未选择站点'
        }}</div>
      </template>
    </float-button>

    <SiteModal @register="register" @change="handleChange" />
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, onMounted } from 'vue';
  import { FloatButton } from 'ant-design-vue';
  import { Icon } from '@/components/Icon';
  import { useModal } from '@/components/Modal';
  import SiteModal from './components/SiteModal.vue';
  import { useCmsStore } from '@/store/modules/cms';
  import { CmsSite } from '@/api/cms/model/cmsSiteModel';
  import { getUserActiveSite } from '@/api/cms/cmsSite';
  export default defineComponent({
    name: 'SiteSelect',
    components: { Icon, SiteModal, FloatButton },
    emits: ['change'],
    setup(_, { emit }) {
      const [register, { openModal }] = useModal();
      const cmsStore = useCmsStore();

      const getCurrentSite = computed(() => {
        return cmsStore.getCurrentSite;
      });

      onMounted(() => {
        if (getCurrentSite.value == null) {
        }
        if (getCurrentSite.value == null) {
          // 如果本地没有设置过当前编辑站点，尝试到服务端获取
          getUserActiveSite().then((site) => {
            if (site) {
              cmsStore.setCurrentSite(site);
            } else {
              openSiteModal();
            }
          });
        }
      });

      function handleChange(site: CmsSite) {
        emit('change', site);
      }

      function openSiteModal() {
        openModal(true, {});
      }

      return {
        getCurrentSite,
        register,
        handleChange,
        openSiteModal,
      };
    },
  });
</script>
<style lang="less" scoped></style>
